﻿using System.Diagnostics.Contracts;

namespace IWMAG.Core.EnhancedProperties.PropertyNodes
{
    internal class ResourceIndirectNode<T> : PropertyNode<T>, IResourceObserver<T>
    {
        public ResourceIndirectNode(int priority, IResource<T> resource) : base(priority)
        {
            Contract.Requires(resource != null);
            backingResource = resource;
            backingResource.AddObserver(this);
        }

        internal void UpdateResource(IResource<T> newResource)
        {
            backingResource.RemoveObserver(this);
            backingResource = newResource;
            backingResource.AddObserver(this);
        }

        private IResource<T> backingResource;
        public override T GetNodeValue()
        {
            return backingResource.Value;
        }

        public override void SuccessorChanged(T value) { }

        public void ResourceChanged(T newValue)
        {
            Previous.SuccessorChanged(newValue);
        }

        public override void Dispose()
        {
            base.Dispose();
            backingResource.RemoveObserver(this);
            backingResource = null;
        }


        public void ResourceDisposed()
        {
            
            var tmp1 = this.Next;
            var tmp2 = this.Previous;
            this.Previous.Next = this.Next;
            this.Next.Previous = this.Previous;

           

            if (tmp2.Next.Previous == null)
            {
                tmp2.NotifyListModified();
            }
            else
            {
                tmp1.NotifyListModified();
            }

            tmp2.SuccessorChanged(tmp1.GetNodeValue());

            base.Dispose();
            backingResource = null;
        }
    }
}
